package game;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class Movement {
	
	private Model model;
	
	private long previousMovement = System.currentTimeMillis();
	
	private long timeElapsed;
	
	public Movement(Model model) {
		this.model = model;
	}

	private List<MovingSprite> movingSprites = new CopyOnWriteArrayList<MovingSprite>();
	
	public void registerForMovement(MovingSprite sprite) {
		synchronized(movingSprites) {
			movingSprites.add(sprite);
		}
	}
	
	public void remove(MovingSprite sprite) {
			movingSprites.remove(sprite);
	}
	
	public void move() {
		timeElapsed = System.currentTimeMillis() - previousMovement;
		previousMovement = System.currentTimeMillis();
		for (MovingSprite s : movingSprites) {
			moveSprite(s);
		}
	}
	
	
	
	private void moveSprite(MovingSprite me) {
		
		if (me.getHorizontalDirection() != Direction.NONE || me.getVerticalDirection() != Direction.NONE) {
			int x = me.getX();
			int y = me.getY();
			int x1 = me.getX1();
			int y1 = me.getY1();
			
			int newx = x;
			int newy = y;
			int newx1 = x1;
			int newy1 = y1;
			
			int movementLength = (int) (me.getSpeed() * timeElapsed);
			newx += movementLength * me.getHorizontalDirection().getSign();
			newy += movementLength * me.getVerticalDirection().getSign();
			newx1 = newx + me.getWidth();
			newy1 = newy + me.getHeight();

			ArrayList<Collision> collisions = model.collides(me, x, y, x1, y1, newx, newy, newx1, newy1);
		
			if (collisions.size() > 0) me.triggerCollision(collisions);
			
			for (Collision collision : collisions) {

				Sprite hitObject = collision.getObject();
				Direction hitDirection = collision.getSide();
				
				int hox = hitObject.getX();
				int hoy = hitObject.getY();
				int hox1 = hox + hitObject.getWidth();
				int hoy1 = hoy + hitObject.getHeight();
				
				if (hitDirection == Direction.LEFT) {
					newx = hox1;
				}
				else if (hitDirection == Direction.RIGHT) {
					newx = hox - me.getWidth();
				}
				else if (hitDirection == Direction.UP) {
					newy = hoy1;
				}
				else if (hitDirection == Direction.DOWN) {
					newy = hoy - me.getHeight();
				}
			}
						
			me.setCoordinates(newx, newy);
		}	
	}
	
}
